package com.ruoyi.common.utils.poi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Author: MMDZ
 * @Desc: TODO map 导出
 */
public class MapExcelUtil {
    private static final Logger log = LoggerFactory.getLogger(MapExcelUtil.class);

    /**
     * @param response
     * @param heads     所有标题头（中文）
     * @param tempHeads 所有标题头（数据key）
     * @param list      导出Map集合数据
     * @param sheetName 工作表名称
     * @return
     */
    public static void exportExcel(HttpServletResponse response, List<String> heads, List<String> tempHeads, List<Map<String, Object>> list, String sheetName) {
        // 创建工作簿 (每多少行会被保存到磁盘)
        SXSSFWorkbook workbook = new SXSSFWorkbook(500);
        // 创建工作表 sheet对象
        SXSSFSheet sheet = workbook.createSheet(sheetName);
        // 样式列表
        Map<String, CellStyle> styleMap = createStyles(workbook);

        // 创建第一行对象 列标题,并且设置列标题
        Row titleRow = sheet.createRow(0);
        int titleNum = heads.size();
        //设置表头
        for (int i = 0; i < titleNum; i++) {
            Cell titleCell = titleRow.createCell(i);
            titleCell.setCellStyle(styleMap.get("header"));
            titleCell.setCellValue(heads.get(i));
        }

        //将数据写入Excel
        if (list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                //创建行数据
                Row dataRow = sheet.createRow(i + 1);
                //临时数据存储集合
                List<Object> data = new ArrayList<Object>();

                for (int i1 = 0; i1 < tempHeads.size(); i1++) {
                    data.add(list.get(i).get(tempHeads.get(i1)));
                }

                for (int j = 0; j < data.size(); j++) {
                    //创建单元格
                    Cell titleCell = dataRow.createCell(j);
                    titleCell.setCellStyle(styleMap.get("data"));
                    if ("null".equals(String.valueOf(data.get(j))) || String.valueOf(data.get(j)) == null) {
                        titleCell.setCellValue("");
                    } else {
                        titleCell.setCellValue(String.valueOf(data.get(j)));
                    }
                }
            }
        }

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        try {
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
        } finally {
            IOUtils.closeQuietly(workbook);
        }
    }

    /**
     * 创建表格样式
     *
     * @param wb 工作薄对象
     * @return 样式列表
     */
    private static Map<String, CellStyle> createStyles(Workbook wb) {
        // 写入各条记录,每条记录对应excel表中的一行
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        CellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        Font titleFont = wb.createFont();
        titleFont.setFontName("Arial");
        titleFont.setFontHeightInPoints((short) 16);
        titleFont.setBold(true);
        style.setFont(titleFont);
        styles.put("title", style);

        style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderRight(BorderStyle.THIN);
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderLeft(BorderStyle.THIN);
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderTop(BorderStyle.THIN);
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderBottom(BorderStyle.THIN);
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        Font dataFont = wb.createFont();
        dataFont.setFontName("Arial");
        dataFont.setFontHeightInPoints((short) 10);
        style.setFont(dataFont);
        styles.put("data", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font headerFont = wb.createFont();
        headerFont.setFontName("Arial");
        headerFont.setFontHeightInPoints((short) 10);
        headerFont.setBold(true);
        headerFont.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(headerFont);
        styles.put("header", style);

        style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        Font totalFont = wb.createFont();
        totalFont.setFontName("Arial");
        totalFont.setFontHeightInPoints((short) 10);
        style.setFont(totalFont);
        styles.put("total", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.LEFT);
        styles.put("data1", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        styles.put("data2", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.RIGHT);
        styles.put("data3", style);
        return styles;
    }

}
